<template>
  <div ref="chartRef" :style="{ width, height }" />
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import { useElementSize, useResizeObserver } from '@vueuse/core'

const props = defineProps<{
  options: EChartsOption
  width?: string
  height?: string
}>()

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

onMounted(() => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    chart.setOption(props.options)
  }
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
  }
})

// 监听容器大小变化
if (chartRef.value) {
  const { width, height } = useElementSize(chartRef)
  useResizeObserver(chartRef, () => {
    chart?.resize({
      width: width.value,
      height: height.value,
    })
  })
}

// 监听配置变化
watch(
  () => props.options,
  (newOptions) => {
    chart?.setOption(newOptions, true)
  },
  { deep: true },
)
</script>
